package com.example.demo.test;


import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName zabbix_client_factory
 * @Description
 * @date 2022/11/10 17:38
 * @Author yanceysong
 * @Version 1.0
 */
public class monitor_client_factory implements AutoCloseable {
    public static final int WINDOWS = 0;
    public static final int LINUX = 1;


    private static final ConcurrentHashMap<String, monitor_inter> monitor_pool = new ConcurrentHashMap<>();


    /**
     * 获取zibbix客户端
     *
     * @return 客户端
     */
    public static monitor_inter get_client(String ip, int type) {
        if (!monitor_pool.containsKey(ip)) {
            monitor_pool.put(ip, type == monitor_client_factory.WINDOWS ? null : new linux_monitor(ip));
        }
        return monitor_pool.get(ip);
    }

    /**
     * 关闭服务器的连接
     *
     * @param ip 地址
     */
    public static void close(String ip) {
        monitor_pool.get(ip).close();
        monitor_pool.remove(ip);

    }

    /**
     * 如果客户端失效可以利用该方法更新客户端
     *
     * @return 更新后客户端
     */
    public monitor_inter update_zabbix_client(String ip, int type) {
        monitor_pool.remove(ip);
        return get_client(ip, type);
    }

    /**
     * 自动关闭，避免浪费资源
     *
     * @throws Exception 异常
     */
    @Override
    public void close() throws Exception {
        for (String ip : monitor_pool.keySet()) {
            monitor_client_factory.close(ip);
        }
    }
}
